function Tab (id) {
	this.main = document.querySelector(id)
	this.add = document.querySelector('.tabadd')
	this.ul = this.main.querySelector('.fisrstnav ul')
	this.contents = document.querySelector('.tabscon')
	this.init()
}
Tab.prototype = {
	constructor:Tab,
	init:function(){
		this.lis = this.main.querySelectorAll('li')
		this.sections = this.main.querySelectorAll('section')
		this.remove = this.main.querySelectorAll('.icon-guanbi')
		this.editSpan = this.main.querySelectorAll('.fisrstnav li span:first-child')
		for(var i=0;i<this.lis.length;i++){
			this.lis[i].setAttribute('data-index',i)
			this.lis[i].onclick = this.toggleTab(this)
			this.remove[i].onclick = this.removeTab(this)
			this.editSpan[i].ondblclick = this.editTab(this);
			this.sections[i].ondblclick = this.editTab(this);
		}
		this.add.onclick = this.addTab(this)
	},
	toggleTab:function(that){
		return function(){
			for(var i = 0;i<that.lis.length;i++){
				that.lis[i].className = ''
				that.sections[i].className = ''
			}
			this.className = 'liactive'
			that.sections[this.dataset.index].className = 'conactive'
		}
	},
	addTab:function(that){
		return function(){
			var li = '<li><span>测试</span><span class="iconfont icon-guanbi"></span></li>'
			var section = '<section>测试'+Math.random()+'</section>'
			that.ul.insertAdjacentHTML('beforeEnd',li)
			that.contents.insertAdjacentHTML('beforeEnd',section)
			
			that.init()
		}
	},
	removeTab:function(that){
		return function(e){
			e.stopPropagation(); // 阻止冒泡 防止触发li 的切换点击事件
			var index = this.parentNode.dataset.index;
			console.log(index);
			// 根据索引号删除对应的li 和section   remove()方法可以直接删除指定的元素
			that.lis[index].remove();
			that.sections[index].remove();
			that.init();
			// 当我们删除的不是选中状态的li 的时候,原来的选中状态li保持不变
			if (document.querySelector('.liactive')) return;
			// 当我们删除了选中状态的这个li 的时候, 让它的前一个li 处于选定状态
			index--;
			// 手动调用我们的点击事件  不需要鼠标触发
			that.lis[index] && that.lis[index].click();
			that.init()
		}
	},
	editTab:function(that){
		return function(){
			var str = this.innerHTML;
			// 双击禁止选定文字
			window.getSelection ? window.getSelection().removeAllRanges() : 				    document.selection.empty();
			// alert(11);
			this.innerHTML = '<input type="text" />';
			var input = this.children[0];
			input.value = str;
			input.select(); // 文本框里面的文字处于选定状态
			// 当我们离开文本框就把文本框里面的值给span 
			input.onblur = function() {
				this.parentNode.innerHTML = this.value;
			};
			// 按下回车也可以把文本框里面的值给span
			input.onkeyup = function(e) {
			    if (e.keyCode === 13) {
			        // 手动调用表单失去焦点事件  不需要鼠标离开操作
			        this.blur();
			    }
			}
		}
	}
}
new Tab('#tab')